package com.dragon8869.myspringboot.service.impl;

import com.dragon8869.myspringboot.entity.AyUser;
import com.dragon8869.myspringboot.service.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(List<AyUser> ayUsers) throws MessagingException, UnsupportedEncodingException {
        if (ayUsers == null || ayUsers.size() == 0) {
            return;
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setFrom(from, "服务器");
        mimeMessageHelper.setSubject("地瓜今日特卖");
        mimeMessageHelper.setText("您知道吗？厦门地瓜今日特卖，一斤只要9元！");
        for (AyUser ayUser : ayUsers) {
            if (!StringUtils.hasLength(ayUser.getEmail())) {
                continue;
            }
            mimeMessageHelper.addTo(ayUser.getEmail(), ayUser.getName());
        }
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void sendMail(AyUser ayUser) throws UnsupportedEncodingException, MessagingException {
        if (ayUser == null || !StringUtils.hasLength(ayUser.getEmail())) {
            return;
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setFrom(from, "服务器");
        mimeMessageHelper.setSubject("地瓜今日特卖");
        mimeMessageHelper.setText("您知道吗？厦门地瓜今日特卖，一斤只要9元！");
        mimeMessageHelper.addTo(ayUser.getEmail(), ayUser.getName());
        javaMailSender.send(mimeMessage);

    }

}
